package com.itheima.tanhua.apiImpl;


import cn.hutool.core.collection.CollUtil;
import com.itheima.tanhua.api.mongodb.FriendApi;
import com.itheima.tanhua.pojo.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;




    //查找friend数据
    @Override
    public void saveContacts(Long uid, Long friendId) {

        Query query1=Query.query(Criteria.where("userId").is(uid).and("friendId").is(friendId));
        //exists 检测是否存在
        if (!mongoTemplate.exists(query1, Friend.class)){
            //添加数据到mongodb
            Friend friend=new Friend();
            friend.setUserId(uid);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        Query query2=Query.query(Criteria.where("userId").is(friendId).and("friendId").is(uid));
        //exists 检测是否存在
        if (!mongoTemplate.exists(query2, Friend.class)){
            //添加数据到mongodb
            Friend friend=new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(uid);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    @Override
    public List<Long> findFriendIds(Long uid) {
        Query query=Query.query(Criteria.where("userId").is(uid));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return CollUtil.getFieldValues(friends, "friendId", Long.class);
    }

    //删除两用户之间的好友关系
    @Override
    public void delete(Long uid, Long likeUserId) {

          //好友关系是相互的删除的是一对
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(uid).and("friendId").is(likeUserId)));
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(likeUserId).and("friendId").is(uid)));
    }
}
